﻿/*
 * 实验任务.
 * 
 * 2009-6-3 szj
 * */


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using EQT.Model;
using EQT.Dal;

public partial class TaskView : System.Web.UI.Page
{
    private readonly DaContract daContract=new DaContract(DaCommon.DefaultDb);
    private readonly DaCoTestItem dacti = new DaCoTestItem(DaCommon.DefaultDb);//合同检验项
    private readonly DaTfile datfile = new DaTfile(DaCommon.DefaultDb);
    private readonly DaTestRecord datr = new DaTestRecord(DaCommon.DefaultDb);
    private readonly DaReportAudit dara = new DaReportAudit(DaCommon.DefaultDb);

    internal UserContext uc;

    //默认情况下：
    //检验任务根据角色而变化。
    //业务组能够看进度，但不能操作
    //实验组能够看分派给当前组的任务；
    //管理员无限制


    protected void Page_Load(object sender, EventArgs e)
    {
        uc = (UserContext)Session["USER_CONTEXT"];
        if(!Page.IsPostBack)
        {   
            BindToDoContracts();            

            #region Note:这里做权限检查
            //DTT_MANAGE_TEST_TASK 执行测试任务
            //DTT_MANAGE_CO_TEST_ITEM 管理测试项
            //RPT_GENERATE_REPORT  生成报告
            //RPT_CONFIRM_1 专家审核
            //RPT_CONFIRM_LAST 站长审核
            GridViewContracts.Columns[5].Visible = Utility.CheckRights(FuncIdConstants.DTT_MANAGE_TEST_TASK, this); 

            //如可以管理测试项，则4，5，6，7列可以显示，否则不能显示
            if (Utility.CheckRights(FuncIdConstants.DTT_MANAGE_CO_TEST_ITEM, this) == false)
            {
                for (int i = 4; i < 8; i++)
                {
                    GridViewTestItems.Columns[i].Visible = false;
                }
                //原始记录删除按钮列不可见
                GridViewTestRecords.Columns[4].Visible = false;
            }
           
            #endregion

        }
    }
   
    /// <summary>
    /// 开始测试项的试验
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnStartTestItem_Click(object sender, EventArgs e)
    {    
#if V1
        Button btn = sender as Button;
        if (btn != null) btn.Enabled = false;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string co_item_id = (string)GridViewTestItems.DataKeys[gvr.RowIndex].Value;
        if (dacti.UpdateTestItemStatus(co_item_id, (int)CO_Test_Item_Status.Doing) > 0)
        {
            btn.Enabled = false;
        }
        BindTestItems(LabelContractId.Text);
#endif
    }

    /// <summary>
    /// 完成执行检验项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnEndTestItem_Click(object sender, EventArgs e)
    {
#if V1
        Button btn = sender as Button;
        if (btn != null) btn.Enabled = false;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string co_item_id = (string)GridViewTestItems.DataKeys[gvr.RowIndex].Value;
        if (dacti.UpdateTestItemStatus(co_item_id, (int)CO_Test_Item_Status.Finished) > 0)
        {
            btn.Enabled = false;
            UserContext uc = Session["USER_CONTEXT"] as UserContext;
            DaActLog.LogOperation(uc.UserID, "NORMAL_ACT", String.Format("完成检验项:{0}.", co_item_id));
        }
        BindTestItems(LabelContractId.Text);
#endif
    }

    /// <summary>
    /// 开始执行合同
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnStartContract_Click(object sender, EventArgs e)
    {
        //开始执行测试，则需更改合同的状态为正处于执行中，
        //只要有一个人开始执行了，合同就开始执行了
        Button btn = sender as Button;
        GridViewRow gvr = (GridViewRow)btn.NamingContainer;
        string report_id = (string)GridViewContracts.DataKeys[gvr.RowIndex].Value;
        //实验组开始执行测试，这将清除业务组相关的掩码位
        daContract.ReplaceContractStatus(report_id, (int)ContractStatus.Testing,
            (int)ContractStatus.BizGrpMask);

        UserContext uc = Session["USER_CONTEXT"] as UserContext;
        DaActLog.LogOperation(uc.UserID, "NORMAL_ACT", String.Format("开始执行测试:{0}.", report_id));

        BindToDoContracts();       

    }
    


    /// <summary>
    /// 绑定待处理的合同，待处理的合同的状态是：待实验,实验中,试验完成    
    /// </summary>
    private void BindToDoContracts()
    {      
        //确定[开始]执行任务列是否显示
        
        DataSet ds = daContract.GetContractsByStatus(DaContract.TEST_GRP_CAN_OPT_CONTRACTS_STATUS);
        GridViewContracts.DataSource = ds;
        GridViewContracts.DataBind();//绑定过程中会检查谁被选中了  
    }
    protected void GridViewContracts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            if (drv != null)
            {
                //根据合同状态来设定按钮
                int rs=(int) drv["Report_Status"];
                string rid = (string)drv["Report_ID"];
                if ((rs & (int)ContractStatus.TestGrp) >= (int)ContractStatus.Testing && GridViewContracts.Columns[5].Visible)
                {
                    Button btn = (Button)e.Row.FindControl("BtnStartContract");
                    btn.Visible = false;                  
                }
               
            }
        }
    }
    /// <summary>
    /// 选择的合同改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewContracts_SelectedIndexChanged(object sender, EventArgs e)
    {
        int idx = GridViewContracts.SelectedIndex;
        GridViewRow gvr = GridViewContracts.Rows[idx];
        if (gvr.RowType == DataControlRowType.DataRow)
        {          
            string report_id= GridViewContracts.SelectedDataKey.Value.ToString();
            MoContract m = daContract.GetEntity(report_id);
            if (m != null)
            {
                LabelContractId.Text = report_id;
                LabelContractId2.Text = report_id;
                BindReportInfo(m);
                BindTestItems(report_id);
                BindTestRecords(report_id);
                              

            }//找不到合同
            else
            {
                Utility.SiteError(String.Format("数据库完整性被破坏！给定的报告编号{0}无效！", report_id));
            }  

        }
    }

    /// <summary>
    /// 当选择的合同发生改变时，会调用这个函数来绑定页面值.
    /// </summary>
    /// <param name="m"></param>
    private void BindReportInfo(MoContract m)
    {
#if V1
        PanelContractTask.Visible = true;
        #region 单个报告的特定的权限
        PanelReport.Visible = Utility.CheckRights(FuncIdConstants.RPT_GENERATE_REPORT, this);

        PanelConfirm.Visible = Utility.CheckRights(FuncIdConstants.RPT_CONFIRM_1, this) ||
        Utility.CheckRights(FuncIdConstants.RPT_CONFIRM_LAST, this);
        //两个按钮只能显示一个
        //当审批人是你时，才应显示           
        BtnConfirm1.Visible = Utility.CheckRights(FuncIdConstants.RPT_CONFIRM_1, this);
        ButtonLastConfirm.Visible = Utility.CheckRights(FuncIdConstants.RPT_CONFIRM_LAST, this);
        #endregion


        //报告组相关
        if (PanelReport.Visible)
        {
            UserContext uc=Session["USER_CONTEXT"] as UserContext;


            if (!String.IsNullOrEmpty(m.Report_Url))
            {
                MoTfile f = datfile.GetEntity(m.Report_Url);
                HyperLinkReport.Text = Server.HtmlEncode(f.File_Name);
                HyperLinkReport.NavigateUrl = String.Format("~/getfile.aspx?fileid={0}", f.File_Id);
            }
            else
            {
                HyperLinkReport.Text = Server.HtmlEncode("<<未上传最终报告>>");
                HyperLinkReport.NavigateUrl = "#";
            }
            //这里设置选择审批人的脚本
            BtnSelectAuditor.Attributes.Add("OnClick", "InvokePopSelectAuditor('" + m.Report_Id + "')");
            //审批人列表，以字符串形式表达
            LabelAuditors.Text = Server.HtmlEncode(dara.GetReportAuditorNames(m.Report_Id, SiteConfig.REPORT_AUDIT_FLOW_1_EXPERT_AUDIT));
            //TODO:检查当前用户是否审核专家

            BtnUploadReport.Attributes.Add("OnClick", "InvokePopUploadFinalReport('" + m.Report_Id + "')");

            
            int status=m.Report_Status & (int)ContractStatus.Clear_Pay_Flag;
            ContractStatus cs = (ContractStatus)status;
            if ((cs < ContractStatus.Confirming1) && ((cs & ContractStatus.WaitConfirm1) > 0))
            {
                BtnConfirm1.Visible = dara.IsAuditor(m.Report_Id, SiteConfig.REPORT_AUDIT_FLOW_1_EXPERT_AUDIT, uc.UserID);
            }
            else
            {
                BtnConfirm1.Visible = false;
            }
        }
#endif
    }
    /// <summary>
    /// 绑定合同测试项，应该只绑定当前实验组的
    /// </summary>
    /// <param name="report_id"></param>
    private void BindTestItems(string report_id)
    {
        UserContext uc = (UserContext)Session["USER_CONTEXT"];

        string where ;
        if (uc.RoleID.StartsWith(UserContext.ROLE_ID_TESTER_GROUP))//是大电流组或强电流组，测试组角色必须以TesterGroup开头
        {
            where = String.Format(" WHERE Report_ID='{0}' AND Charge_Dept_Code='{1}'", report_id,uc.DeptID);
        }
        else
        {
            where = String.Format(" WHERE Report_ID='{0}' ", report_id);
        }
        
        GridViewTestItems.DataSource = dacti.Query(where);
        GridViewTestItems.DataBind();
    }

   

    /// <summary>
    /// 原始记录文件
    /// </summary>
    private void BindTestRecords(string report_id)
    {
#if V1
        GridViewTestRecords.DataSource = datr.GetTestRecordsByReportId(report_id);
        GridViewTestRecords.DataBind();
#endif
    }
  
    /// <summary>
    /// 删除原始记录行
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewTestRecords_RowDeleting(object sender, GridViewDeleteEventArgs e)
    { 
#if V1
        string tr_id= (string)GridViewTestRecords.DataKeys[e.RowIndex].Value;
        MoTestRecord mo_tr = datr.GetEntity(tr_id);
        MoCoTestItem mo_coti = dacti.GetEntity(mo_tr.Co_Item_Id);
        if (mo_coti.Test_Status == (int)CO_Test_Item_Status.Finished)
        {
            Utility.GlobalLog.WarnFormat("不允许删除已经完成的测试项的原始记录.{0},{1}", mo_tr, mo_coti);
            return;
        }

        MoTfile mo_xls = datfile.GetEntity(mo_tr.Tr_Url);          //得到原始记录文件对象
        MoTfile mo_doc = datfile.GetEntity(mo_tr.Report_Slice_Url);//报告片段文件对象

        try
        {
            if (mo_xls != null)
            {
                string file_path_xls = Utility.GetLocalFileFromUri(mo_xls.File_Url);
                System.IO.File.Delete(file_path_xls);//从文件系统删除原始文件
                datfile.Delete(mo_xls);              //删除原始文件的文件记录
                Utility.GlobalLog.WarnFormat("删除原始记录文件{0}", mo_xls.File_Url);
            }

            if (mo_doc != null)
            {
                string file_path_doc = Utility.GetLocalFileFromUri(mo_doc.File_Url);
                System.IO.File.Delete(file_path_doc);//从文件系统删除报告片段文件
                datfile.Delete(mo_doc);              //删除原始文件的文件记录
                Utility.GlobalLog.WarnFormat("删除原始记录文件{0}", mo_doc.File_Url);
            }
            datr.Delete(mo_tr);
            UserContext uc = Session["USER_CONTEXT"] as UserContext;
            DaActLog.LogOperation(uc.UserID,"NORMAL_ACT",String.Format("删除原始记录文件:{0}.{1}.",mo_tr,mo_coti));

        }
        catch (Exception ex)
        {
            Utility.GlobalLog.Error("删除文件失败!", ex);
            Utility.SiteError("删除文件失败！", Response);
        }
        BindTestRecords(LabelContractId.Text);
#endif
    }

    /// <summary>
    /// 绑定一行测试检验项时的特殊处理
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewTestItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
#if V1
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;         
   
            Button btn1 = (Button)e.Row.FindControl("BtnStartTestItem");
            Button btn2 = (Button)e.Row.FindControl("btnDownload");
            Button btn3 = (Button)e.Row.FindControl("btnUpload");
            Button btn4 = (Button)e.Row.FindControl("BtnEndTestItem");

            //2009-6-11 若当前用户是实验组的人，就判断它的任务项 ,这里可能有点多此一举
            string item_code = drv["ITEM_CODE"].ToString();
            if (uc.RoleID==UserContext.ROLE_ID_ADMINISTRATORS || 
                (uc.RoleID.StartsWith(UserContext.ROLE_ID_TESTER_GROUP) &&  dacti.CheckTestItemDept(item_code, uc.DeptID)) 
                )
            {
                int status = (int)drv["Test_Status"];
                CO_Test_Item_Status flag = (CO_Test_Item_Status)status;
                #region 根据项状态判断按钮可用性
                switch (flag)
                {
                    case CO_Test_Item_Status.WaitToStart://待开始
                        {
                            btn1.Enabled = true;
                            btn2.Enabled = false;
                            btn3.Enabled = false;
                            btn4.Enabled = false;
                            break;
                        }
                    case CO_Test_Item_Status.Doing://进行中
                        {
                            btn1.Enabled = false;
                            btn2.Enabled = true;
                            btn3.Enabled = true;
                            btn4.Enabled = true;
                            break;
                        }
                    case CO_Test_Item_Status.Finished://已完成
                        {
                            btn1.Enabled = false;
                            btn2.Enabled = true;
                            btn3.Enabled = false;
                            btn4.Enabled = false;
                            break;
                        }
                    default:
                        {
                            btn1.Enabled = false;
                            btn2.Enabled = false;
                            btn3.Enabled = false;
                            btn4.Enabled = false;
                            break;
                        }
                }
                #endregion

                //添加弹出窗口脚本
                if (btn2.Visible ) btn2.Attributes.Add("OnClick", "InvokePopDownloadTemplate('" + drv["Item_Code"] + "','" + drv["Co_Item_ID"] + "')");
                if (btn3.Visible ) btn3.Attributes.Add("OnClick", "InvokePop('" + drv["Co_Item_ID"] + "')");

            }
            else
            {
                e.Row.Cells[4].Controls.Clear();
                e.Row.Cells[5].Controls.Clear();
                e.Row.Cells[6].Controls.Clear();
                e.Row.Cells[7].Controls.Clear();
            }

        }
        
#endif

    }

   
    /// <summary>
    /// 先弹出窗口上传文件，然后刷新。这里实际是刷新代码。
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnUploadReport_Click(object sender, EventArgs e)
    {

        string report_id = LabelContractId.Text;
        if (!String.IsNullOrEmpty(report_id))
        {
            MoContract m = daContract.GetEntity(report_id);
            BindReportInfo(m);
            UserContext uc = Session["USER_CONTEXT"] as UserContext;
            DaActLog.LogOperation(uc.UserID, "NORMAL_ACT", String.Format("上传报告:{0}.", m));
        }
    }
    /// <summary>
    /// 删除当前已经上传的报告
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnDeleteReport_Click(object sender, EventArgs e)
    {
        string report_id = LabelContractId.Text;
        if (!String.IsNullOrEmpty(report_id))
        {
            daContract.DeleteContractReport(report_id);
            MoContract m = daContract.GetEntity(report_id);
            BindReportInfo(m);
            UserContext uc = Session["USER_CONTEXT"] as UserContext;
            DaActLog.LogOperation(uc.UserID, "NORMAL_ACT", String.Format("删除报告:{0}.", report_id));
        }
    }
    /// <summary>
    /// 重新绑定审批人
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnSelectAuditor_Click(object sender, EventArgs e)
    {
        LabelAuditors.Text = Server.HtmlEncode(dara.GetReportAuditorNames(LabelContractId.Text, SiteConfig.REPORT_AUDIT_FLOW_1_EXPERT_AUDIT));
    }

    /// <summary>
    /// 刷新原始记录文件列表
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnHiddenAddTRFile_Click(object sender, EventArgs e)
    {
        BindTestRecords(LabelContractId.Text);
    }
}
